package com.wep.fence.domain;

import cn.hutool.core.map.MapUtil;
import com.fasterxml.jackson.annotation.JsonView;
import com.wep.fence.constant.Constants;
import lombok.Data;
import lombok.ToString;

import java.io.Serial;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 响应信息主体
 *
 * @author wep
 */
@ToString
@Data
public class R<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;
    @JsonView(JsonData.class)
    private int code;
    @JsonView(JsonData.class)
    private String msg = "操作成功！";
    @JsonView(JsonData.class)
    private T data;

    public static <T> R<T> ok() {
        return restResult(null, Constants.SUCCESS, "操作成功");
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, Constants.SUCCESS, "操作成功");
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, Constants.SUCCESS, msg);
    }

    public static <T> R<T> failed() {
        return restResult(null, Constants.FAIL, "操作失败");
    }

    public static <T> R<T> failed(String msg) {
        return restResult(null, Constants.FAIL, msg);
    }

    public static <T> R<T> failed(T data) {
        return restResult(data, Constants.FAIL, null);
    }

    public static <T> R<T> failed(int code, String msg) {
        return restResult(null, code, msg);
    }

    private static <T> R<T> restResult(T data, int code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    public R<T> addExt(String key, Object value) {
        Map<String, Object> ext = new HashMap<>();
        if (Objects.isNull(value)) {
            return this;
        }
        if (MapUtil.isEmpty(ext)) {
            ext = new HashMap<>();
        }
        ext.put(key, value);
        return this;
    }


    public interface JsonData {
    }
}